package com.seed.uaa.login.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryChain;
import com.seed.core.exception.UserAuthenticateException;
import com.seed.core.pojo.Account;
import com.seed.core.pojo.LoginDTO;
import com.seed.uaa.login.Login;
import com.seed.uaa.tenant.web.Tenant;
import com.seed.uaa.util.EncryptUtil;
import com.seed.uaa.util.LoginCheckUtil;
import com.seed.uaa.util.StpKit;
import com.seed.uaa.web.organization.Organization;

import static com.seed.uaa.tenant.web.table.TenantTableDef.TENANT;
import static com.seed.uaa.web.organization.table.OrganizationTableDef.ORGANIZATION;

/**
 * 租户租户名登录
 */
public class TenantUsernameLogin implements Login {
    @Override
    public void login(Account account, LoginDTO dto) {
        Tenant tenant = QueryChain.of(Tenant.class)
                .where(TENANT.TENANTNAME.eq(account.getValue()))
                .one();
        checkTenantLogin(tenant);

        String rawPassword = dto.getPassword();
        String encrypt = EncryptUtil.encrypt(rawPassword, tenant.getSalt());
        if(!encrypt.equals(tenant.getPassword())) {
            throw new UserAuthenticateException("用户名或密码错误");
        }

        StpKit.login(account.getLoginId());
    }

    private void checkTenantLogin(Tenant tenant) {
        LoginCheckUtil.checkLogin(tenant);

        String organizationId = tenant.getOrganizationId();
        if(StrUtil.isNotBlank(organizationId)) {
            Organization organization = QueryChain.of(Organization.class)
                    .where(ORGANIZATION.ID.eq(organizationId))
                    .one();
            LoginCheckUtil.checkLogin(organization);
            checkAncestorLogin(organization);
        }
    }

    private void checkAncestorLogin(Organization organization) {
        String parentId = organization.getParentId();
        while (StrUtil.isNotBlank(parentId)) {
            organization = QueryChain.of(Organization.class)
                    .where(ORGANIZATION.ID.eq(parentId))
                    .one();
            LoginCheckUtil.checkAncestorLogin(organization);
            parentId = organization.getParentId();
        }
    }
}
